/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.beepmystuff;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.beepmystuff.NetworkService.NetworkServiceConnection;

/**
 * An activity to get the user's credentials and to let them test them
 * interactively.
 */
public class LoginActivity extends Activity {
  private NetworkServiceConnection networkServiceConnection = new NetworkServiceConnection();
  private NetworkService networkService;
  private TextView nickname;
  private TextView password;
  private Preferences preferences;

  /**
   * Called when the activity is first created.
   * */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.BeepMyStuffDialog);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    // Establish a connection with our service (starting it if necessary).
    NetworkService.bind(this, networkServiceConnection,
        new Runnable() {
          @Override
          public void run() {
            networkService = networkServiceConnection.getService();
            createAfterServiceAvailable();
          }
    });

    // Enable the web link in the explanatory text.
    // See http://code.google.com/p/android/issues/detail?id=2219
    TextView explanatoryText = (TextView) findViewById(R.id.explanatory_text);
    explanatoryText.setMovementMethod(LinkMovementMethod.getInstance());

    preferences = Injector.getInjector(getApplication()).getPreferences();
    nickname = (TextView) findViewById(R.id.nickname);
    nickname.setText(preferences.getNickname());
    password = (TextView) findViewById(R.id.password);
    password.setText(preferences.getPassword());
  }

  /** Continue creation after the network service has been started. */
  private void createAfterServiceAvailable() {
    Button loginButton = (Button) findViewById(R.id.login);
    loginButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
        new LoginTask().execute();
      }
    });
  }

  /**
   * Called before the activity is destroyed.
   */
  @Override
  public void onDestroy() {
    super.onDestroy();
    unbindService(networkServiceConnection);
  }

  /**
   * Asynchronous task to check a username and password.
   */
  private class LoginTask extends AsyncTask<Object, Integer, String> {
    private ProgressDialog loginProgress;

    /**
     * Called on the UI thread before the background thread starts.
     */
    @Override
    protected void onPreExecute() {
      loginProgress = ProgressDialog.show(LoginActivity.this,
          getString(R.string.logging_in_title),
          getString(R.string.logging_in_message),
          true,
          true,
          new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface ignored) {
              cancel(true);
            }
          });
    }

    /**
     * Called on the background thread. We don't use the parameters passed to
     * us, and we return an error string, or null if the login was successful.
     */
    @Override
    protected String doInBackground(Object... ignored) {
      try {
        networkService.login(getNickname(), getPassword());
      } catch (BmsException bms) {
        return bms.getMessage();
      }
      // We succeeded; return a null.
      return null;
    }

    /**
     * Called in the UI thread with the result of doInBackground.
     */
    @Override
    protected void onPostExecute(String error) {
      loginProgress.dismiss();
      if (error != null) {
        new AlertDialog.Builder(LoginActivity.this)
            .setMessage(error)
            .setTitle(R.string.login_failed_title)
            .setPositiveButton(R.string.login_failed_button_title, null)
            .show();
      } else {
        preferences.setNickname(getNickname());
        preferences.setPassword(getPassword());
        Toast.makeText(LoginActivity.this, R.string.logged_in_ok, Toast.LENGTH_SHORT)
            .show();
        finish();
      }
    }
  }

  /** Get the nickname set in the ui. */
  private String getNickname() {
    return nickname.getText().toString();
  }

  /** Get the password set in the ui. */
  private String getPassword() {
    return password.getText().toString();
  }
}
